<template>
	<view class="nx-list">
		<template v-if="useScroll">
			<scroll-view style="height: 100%; width: 100%;" scroll-y="true" :refresher-enabled="useRefresh"
				:refresher-triggered="refreshState" @scrolltolower="scrolltolower" @refresherrefresh="refresh">
				<slot name="main" :list="list"></slot>
				<view class="uni-flex uni-flex-column uni-justify-center uni-align-center"
					v-if="list.length === 0 && loading === false">
					<image class="uni-w-50" src="../static/empty.svg" />
					<text>暂无数据</text>
				</view>
			</scroll-view>
		</template>
		<template v-else>
			<slot name="main" :list="list"></slot>
		</template>
	</view>
</template>
<script>
	export default {
		name: 'nx-list',
		props: {
			api: {
				type: Function,
				default: () => {},
			},
			useScroll: {
				type: Boolean,
				default: true,
			},
			useRefresh: {
				type: Boolean,
				default: true,
			},
			pageConfig: {
				type: Object,
				default: () => {},
			},
			extraParams: {
				type: Object,
				default: () => {},
			}
		},
		data() {
			return {
				list: [],
				refreshState: false,
				index: 0,
				size: 10,
				params: this.handleParams(),
				loading: false,
				loaded: false,
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init: function() {
				this.list = []
				this.getData()
			},
			getData: function() {
				if (this.loaded) {
					return false
				}
				this.loading = true
				let params = {
					...this.params,
					...this.extraParams
				}
				this.api(params).then(res => {
					const data = this.pageConfig.handleData(res)
					this.list = this.list.concat(data)
					const current = this.params[this.pageConfig.currentKey]
					const totalPagesNum = this.pageConfig.getTotalPagesNum(res)
					if (current < totalPagesNum) {
						this.params[this.pageConfig.currentKey] = current + 1
					}
					this.refreshState = false
					this.loading = false
					if (!data.length) {
						this.loaded = true
					}
				})
			},
			search: function() {
				this.reset()
				this.getData()
			},
			scrolltolower: function() {
				this.getData()
			},
			refresh: function() {
				this.refreshState = true
				this.reset()
				this.getData()
			},
			reset: function() {
				this.loaded = false
				this.params = this.handleParams()
				this.list = []
			},
			handleParams: function() {
				return JSON.parse(JSON.stringify(this.pageConfig.params))
			}
		},
	}
</script>
<style lang="scss" scoped>
	.nx-list {
		width: 100%;
		height: 100%;
		overflow: auto;
	}
</style>